from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import re
import time
import requests

def get_token():
    # 替换为 ChromeDriver 的实际路径
    service = Service('path/to/chromedriver')
    driver = webdriver.Chrome(service=service)
    url = 'https://fanyi.baidu.com/'
    try:
        driver.get(url)
        time.sleep(3)  # 等待页面加载完成
        page_source = driver.page_source
        token = re.findall(r"token: '(.*?)',", page_source)
        if token:
            return token[0]
    except Exception as e:
        print(f"获取 token 时出错: {e}")
    finally:
        driver.quit()
    return None

# 后续代码需要根据实际情况调整，因为使用了不同的方式获取 token


def get_sign(word, gtk):
    """
    模拟生成 sign
    此部分逻辑较为复杂，可能需根据百度翻译前端代码更新
    """
    # 以下为简化模拟，实际需参考最新前端逻辑
    a = word
    t = gtk
    e = 503123
    i = ""
    for r in a:
        if ord(r) < 128:
            i += r
        else:
            i += hex(ord(r))[2:]
    n = '320305.131321201'
    s = []
    s.append("fanyideskweb")
    s.append(i)
    s.append(t)
    s.append(n)
    sign = ""
    for char in ''.join(s):
        e = (e << 5) - e + ord(char)
        e &= 0xFFFFFFFF
    sign = f"{e:d}"
    return sign


def translate_word(session, word):
    """
    翻译单词
    """
    token = get_token(session)
    if not token:
        return "未获取到 token，无法进行翻译"
    # 这里 gtk 暂时使用固定值，实际可能需要从页面获取
    gtk = '320305.131321201'
    sign = get_sign(word, gtk)
    url = 'https://fanyi.baidu.com/v2transapi'
    data = {
        'from': 'auto',
        'to': 'zh',
        'query': word,
        'transtype': 'realtime',
        'simple_means_flag': 3,
        'sign': sign,
        'token': token,
        'domain': 'common'
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Referer': 'https://fanyi.baidu.com/'
    }
    try:
        response = session.post(url, data=data, headers=headers)
        response.raise_for_status()
        result = response.json()
        if 'trans_result' in result and 'data' in result['trans_result']:
            return result['trans_result']['data'][0]['dst']
        else:
            return "未获取到有效的翻译结果"
    except requests.RequestException as e:
        return f"请求出错: {e}"
    except ValueError as e:
        return f"解析响应出错: {e}"


if __name__ == "__main__":
    session = requests.Session()
    while True:
        word = input("请输入要翻译的单词（输入 'q' 退出）：")
        if word.lower() == 'q':
            break
        translation = translate_word(session, word)
        print(f"翻译结果: {translation}")
        # 避免频繁请求触发反爬机制
        time.sleep(1)

    